<template>
  <div class="database-table h-full flex flex-col">
    <!-- 工具栏 -->
    <div v-if="showToolbar" class="table-toolbar flex items-center justify-between px-3 py-2 bg-gray-50 border-b">
      <div class="toolbar-left flex items-center space-x-2">
        <!-- 编辑控制按钮 -->
        <el-button-group>
          <el-tooltip content="保存更改 (Ctrl+S)" placement="top" effect="light">
            <el-button 
              size="small" 
              :disabled="!hasChanges"
              @click="saveChanges"
            >
              <el-icon><Check /></el-icon>
              保存
            </el-button>
          </el-tooltip>
          <el-tooltip content="取消所有更改" placement="top" effect="light">
            <el-button 
              size="small" 
              :disabled="!hasChanges"
              @click="cancelChanges"
            >
              <el-icon><Close /></el-icon>
              取消
            </el-button>
          </el-tooltip>
        </el-button-group>
        
        <el-divider direction="vertical" />
        
        <!-- 编辑操作 -->
        <el-button-group>
          <el-tooltip content="撤销 (Ctrl+Z)" placement="top" effect="light">
            <el-button 
              size="small"
              :disabled="!canUndo"
              @click="undo"
            >
              <el-icon><RefreshLeft /></el-icon>
            </el-button>
          </el-tooltip>
          <el-tooltip content="重做 (Ctrl+Y 或 Ctrl+Shift+Z)" placement="top" effect="light">
            <el-button 
              size="small"
              :disabled="!canRedo"
              @click="redo"
            >
              <el-icon><RefreshRight /></el-icon>
            </el-button>
          </el-tooltip>
        </el-button-group>
        
        <el-divider direction="vertical" />
        
        <!-- 数据操作 -->
        <el-button-group>
          <el-tooltip content="插入新行 (Ctrl+N)" placement="top" effect="light">
            <el-button 
              size="small"
              @click="insertRow"
            >
              <el-icon><Plus /></el-icon>
              插入行
            </el-button>
          </el-tooltip>
          <el-tooltip content="删除所选行 (Delete)" placement="top" effect="light">
            <el-button 
              size="small"
              :disabled="selectedRows.length === 0"
              @click="deleteRows"
            >
              <el-icon><Delete /></el-icon>
              删除行
            </el-button>
          </el-tooltip>
        </el-button-group>
        
        <el-divider direction="vertical" />
        
        <!-- 高级功能 -->
        <el-tooltip content="查找/替换 (Ctrl+F)" placement="top" effect="light">
          <el-button 
            size="small"
            @click="openFindReplace"
          >
            <el-icon><Search /></el-icon>
            查找替换
          </el-button>
        </el-tooltip>
      </div>
      
      <div class="toolbar-right flex items-center space-x-2">
        <!-- 视图选项 -->
        <el-checkbox v-model="showLineNumbers">显示行号</el-checkbox>
        <el-checkbox v-model="showModifiedCells">高亮修改</el-checkbox>
        <el-divider direction="vertical" />
        
        <!-- 快捷键帮助 -->
        <el-tooltip placement="bottom" :show-after="100">
          <template #content>
            <div class="shortcuts-list p-2">
              <div class="text-xs font-bold mb-2">表格快捷键</div>
              <div class="grid grid-cols-2 gap-x-4 gap-y-1 text-xs">
                <div>Ctrl+S</div><div>保存更改</div>
                <div>Ctrl+Z</div><div>撤销</div>
                <div>Ctrl+Y / Ctrl+Shift+Z</div><div>重做</div>
                <div>Ctrl+N</div><div>插入新行</div>
                <div>Delete</div><div>删除选中行</div>
                <div>Ctrl+F</div><div>查找/替换</div>
                <div>Ctrl+A</div><div>全选</div>
                <div>Ctrl+C</div><div>复制</div>
                <div>Ctrl+V</div><div>粘贴</div>
                <div>Ctrl+X</div><div>剪切</div>
                <div>F2/Enter</div><div>编辑单元格</div>
                <div>方向键</div><div>移动单元格</div>
              </div>
            </div>
          </template>
          <el-button size="small" circle>
            <el-icon><InfoFilled /></el-icon>
          </el-button>
        </el-tooltip>
      </div>
    </div>
    
    <!-- Canvas 表格 -->
    <canvas-table
      ref="canvasTableRef"
      class="flex-1"
      :columns="tableColumns"
      :data="tableData"
      :options="tableOptions"
      @cell-click="handleCellClick"
      @cell-change="handleCellChange"
      @selection-change="handleSelectionChange"
      @data-change="handleDataChange"
      @column-resize="handleColumnResize"
      @row-resize="handleRowResize"
      @sort="handleSort"
    />
    
    <!-- 状态栏 -->
    <div v-if="showStatusBar" class="table-statusbar flex items-center justify-between px-3 py-1 bg-gray-50 border-t text-xs">
      <div class="status-left flex items-center space-x-4">
        <span v-if="hasChanges" class="text-orange-600 font-medium">
          <el-icon><Edit /></el-icon>
          {{ changeCount }} 个修改未保存
        </span>
        <span v-if="currentCell" class="text-gray-600">
          当前单元格: {{ currentCell.field }}{{ currentCell.row + 1 }}
        </span>
      </div>
      
      <div class="status-right flex items-center space-x-4">
        <span class="text-gray-600">
          共 {{ totalRows }} 行 × {{ totalCols }} 列
        </span>
        <span v-if="selectedCells.length > 0" class="text-blue-600">
          已选择 {{ selectedCells.length }} 个单元格
        </span>
      </div>
    </div>
    
    <!-- 查找替换对话框 -->
    <el-dialog 
      v-model="findReplaceVisible" 
      title="查找和替换" 
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form :model="findReplaceForm" label-width="80px">
        <el-form-item label="查找内容">
          <el-input 
            v-model="findReplaceForm.findText" 
            placeholder="输入要查找的内容"
            @keydown.enter="findNext"
          />
        </el-form-item>
        <el-form-item label="替换为">
          <el-input 
            v-model="findReplaceForm.replaceText" 
            placeholder="输入替换内容"
          />
        </el-form-item>
        <el-form-item label="查找范围">
          <el-select v-model="findReplaceForm.scope" style="width: 100%">
            <el-option label="整个表格" value="all" />
            <el-option label="选中列" value="column" />
            <el-option label="选中区域" value="selection" />
          </el-select>
        </el-form-item>
        <el-form-item label="选项">
          <el-checkbox v-model="findReplaceForm.caseSensitive">区分大小写</el-checkbox>
          <el-checkbox v-model="findReplaceForm.wholeWord">全词匹配</el-checkbox>
          <el-checkbox v-model="findReplaceForm.useRegex">使用正则表达式</el-checkbox>
        </el-form-item>
      </el-form>
      <div class="find-status" v-if="findResults.total > 0">
        找到 {{ findResults.total }} 个匹配项，当前第 {{ findResults.current + 1 }} 个
      </div>
      <template #footer>
        <el-button @click="findNext">查找下一个</el-button>
        <el-button @click="findPrevious">查找上一个</el-button>
        <el-button type="primary" @click="replaceOne">替换</el-button>
        <el-button type="danger" @click="replaceAll">全部替换</el-button>
        <el-button @click="findReplaceVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, onUnmounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Check, Close, RefreshLeft, RefreshRight, Plus, Delete, Edit, Search, InfoFilled
} from '@element-plus/icons-vue'
import CanvasTable from '../canvas-table/CanvasTable.vue'
import { ElTooltip } from 'element-plus'

// Props定义
const props = defineProps({
  // 数据相关
  data: {
    type: Array,
    default: () => []
  },
  columns: {
    type: Array,
    required: true
  },
  
  // 功能开关
  editable: {
    type: Boolean,
    default: true
  },
  showToolbar: {
    type: Boolean,
    default: true
  },
  showStatusBar: {
    type: Boolean,
    default: true
  },
  
  // 数据库相关
  primaryKeys: {
    type: Array,
    default: () => []
  },
  readOnlyColumns: {
    type: Array,
    default: () => []
  },
  
  // 尺寸配置
  defaultRowHeight: {
    type: Number,
    default: 28
  },
  defaultColumnWidth: {
    type: Number,
    default: 120
  },
  
  // 分页信息
  currentPage: {
    type: Number,
    default: 1
  },
  pageSize: {
    type: Number,
    default: 20
  },
  
  // 排序模式
  forceLocalSort: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['save', 'change', 'select', 'column-resize', 'row-resize', 'sort', 'delete-rows'])

// 表格引用
const canvasTableRef = ref(null)

// 状态管理
const selectedCells = ref([])
const selectedRows = ref([])
const currentCell = ref(null)
const showModifiedCells = ref(true)
const showLineNumbers = ref(true)
const hasChanges = ref(false)
const changeCount = ref(0)

// 查找替换相关
const findReplaceVisible = ref(false)
const findReplaceForm = ref({
  findText: '',
  replaceText: '',
  scope: 'all',
  caseSensitive: false,
  wholeWord: false,
  useRegex: false
})
const findResults = ref({
  matches: [],
  current: -1,
  total: 0
})

// 计算属性
const canUndo = computed(() => {
  return canvasTableRef.value?.getTable()?.canUndo() || false
})

const canRedo = computed(() => {
  return canvasTableRef.value?.getTable()?.canRedo() || false
})

const totalRows = computed(() => props.data.length)
const totalCols = computed(() => props.columns.length)

// 转换列配置以适配 Canvas 表格
const tableColumns = computed(() => {
  console.log('DatabaseTable - 接收到的columns:', props.columns)
  console.log('DatabaseTable - 接收到的data:', props.data?.slice(0, 2))
  
  // 获取保存的列宽设置
  const columnWidths = JSON.parse(localStorage.getItem('table-column-widths') || '{}')
  const tableId = `${props.currentPage}_${props.pageSize}`
  const savedWidths = columnWidths[tableId] || {}
  
  return props.columns.map(col => ({
    field: col.field,
    title: col.title + (props.primaryKeys.includes(col.field) ? ' 🔑' : ''),
    width: savedWidths[col.field] || col.width || props.defaultColumnWidth,
    minWidth: 60,
    maxWidth: 600,
    type: col.type,
    editable: props.editable && !props.readOnlyColumns.includes(col.field),
    editType: col.editType || 'text',
    editOptions: col.editOptions || {},
    formatter: (value) => {
      if (value === null || value === undefined) return 'NULL'
      
      // 根据列类型格式化显示
      const colType = (col.type || '').toLowerCase()
      
      // 日期时间格式化
      if (colType.includes('date') || colType.includes('time')) {
        if (value instanceof Date) {
          return value.toLocaleString()
        }
        // 尝试解析字符串日期
        try {
          const date = new Date(value)
          if (!isNaN(date.getTime())) {
            if (colType === 'date') {
              return date.toLocaleDateString()
            } else if (colType === 'time') {
              return date.toLocaleTimeString()
            } else {
              return date.toLocaleString()
            }
          }
        } catch (e) {
          // 解析失败，返回原值
        }
      }
      
      // 布尔值格式化
      if (colType === 'boolean' || colType === 'bool' || colType === 'bit' || colType === 'tinyint(1)') {
        return value ? '✓' : '✗'
      }
      
      // JSON格式化
      if (colType === 'json' || colType === 'jsonb') {
        try {
          return JSON.stringify(value, null, 2)
        } catch (e) {
          return String(value)
        }
      }
      
      // 大文本截断显示
      if (colType.includes('text') || colType.includes('blob')) {
        const str = String(value)
        if (str.length > 100) {
          return str.substring(0, 100) + '...'
        }
      }
      
      // 颜色值显示
      if (col.editType === 'color' && value) {
        // 可以返回带颜色预览的HTML（但CanvasTable可能不支持HTML）
        return String(value)
      }
      
      return String(value)
    },
    validator: (value) => {
      // 必填验证
      if (col.editOptions?.required && (value === null || value === undefined || value === '')) {
        return { valid: false, message: '此字段为必填项' }
      }
      
      // 基本的类型验证
      if (col.type === 'integer' && value !== null) {
        const num = Number(value)
        if (isNaN(num) || !Number.isInteger(num)) {
          return { valid: false, message: '请输入整数' }
        }
      }
      if ((col.type === 'float' || col.type === 'decimal' || col.type === 'double') && value !== null) {
        const num = Number(value)
        if (isNaN(num)) {
          return { valid: false, message: '请输入数字' }
        }
      }
      
      // 邮箱验证
      if (col.editType === 'email' && value) {
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
        if (!emailRegex.test(String(value))) {
          return { valid: false, message: '请输入有效的邮箱地址' }
        }
      }
      
      // URL验证
      if (col.editType === 'url' && value) {
        try {
          new URL(String(value))
        } catch {
          return { valid: false, message: '请输入有效的URL' }
        }
      }
      
      return { valid: true }
    },
    align: col.type === 'integer' || col.type === 'float' || col.type === 'decimal' || col.type === 'double' ? 'right' : 'left'
  }))
})

// 表格数据
const tableData = computed(() => props.data)

// 表格选项
const tableOptions = computed(() => ({
  rowHeight: props.defaultRowHeight,
  headerHeight: 35,
  showRowNumber: showLineNumbers.value,
  showGridLines: true,
  editable: props.editable,
  multiSelect: true,
  columnResize: true,
  keyboardNavigation: true,
  copyPaste: true,
  undoRedo: true,
  virtualScroll: true,
  theme: {
    modifiedBgColor: showModifiedCells.value ? '#fffbe6' : '#fff'
  },
  pagination: {
    currentPage: props.currentPage,
    pageSize: props.pageSize
  },
  sortMode: 'remote'  // 使用远程排序模式
}))

// 处理单元格点击
const handleCellClick = (event) => {
  currentCell.value = {
    row: event.row,
    col: event.col,
    field: tableColumns.value[event.col]?.field
  }
}

// 处理单元格修改
const handleCellChange = (event) => {
  emit('change', {
    type: 'cell',
    row: event.row,
    col: event.col,
    field: event.field,
    value: event.newValue,
    oldValue: event.oldValue
  })
  
  updateChangeStatus()
}

// 处理选择变化
const handleSelectionChange = (cells) => {
  selectedCells.value = cells
  
  // 计算选中的行
  const rows = new Set()
  cells.forEach(cell => {
    rows.add(cell.row)
  })
  selectedRows.value = Array.from(rows)
  
  emit('select', {
    cells: selectedCells.value,
    rows: selectedRows.value
  })
}

// 处理数据变化
const handleDataChange = (data) => {
  updateChangeStatus()
}

// 处理列宽调整
const handleColumnResize = (event) => {
  emit('column-resize', event)
  
  // 可以在这里保存列宽设置到本地存储
  const columnWidths = JSON.parse(localStorage.getItem('table-column-widths') || '{}')
  const tableId = `${props.currentPage}_${props.pageSize}` // 使用一个唯一标识
  if (!columnWidths[tableId]) columnWidths[tableId] = {}
  columnWidths[tableId][props.columns[event.column].field] = event.width
  localStorage.setItem('table-column-widths', JSON.stringify(columnWidths))
}

// 处理行高调整
const handleRowResize = (event) => {
  emit('row-resize', event)
  
  // 可以在这里保存行高设置
  const rowHeights = JSON.parse(localStorage.getItem('table-row-heights') || '{}')
  const tableId = `${props.currentPage}_${props.pageSize}`
  if (!rowHeights[tableId]) rowHeights[tableId] = {}
  rowHeights[tableId][event.row] = event.height
  localStorage.setItem('table-row-heights', JSON.stringify(rowHeights))
}

// 处理排序
const handleSort = (event) => {
  console.log('DatabaseTable - 接收到排序事件:', event)
  // 对于远程排序，直接传递给父组件
  if (canvasTableRef.value?.getTable()?.options.sortMode === 'remote') {
    emit('sort', event)
  }
}

// 更新修改状态
const updateChangeStatus = () => {
  if (canvasTableRef.value) {
    const changes = canvasTableRef.value.getChanges()
    hasChanges.value = changes && (
      changes.modified.length > 0 || 
      changes.inserted.length > 0 || 
      changes.deleted.length > 0
    )
    changeCount.value = changes ? 
      changes.modified.length + changes.inserted.length + changes.deleted.length : 0
  }
}

// 保存更改
const saveChanges = async () => {
  if (!canvasTableRef.value) return
  
  const changes = canvasTableRef.value.getChanges()
  
  console.log('保存的更改:', changes)
  
  emit('save', changes)
  
  // 提交更改
  canvasTableRef.value.commit()
  updateChangeStatus()
}

// 取消更改
const cancelChanges = async () => {
  if (!canvasTableRef.value) return
  
  // 回滚更改
  canvasTableRef.value.rollback()
  updateChangeStatus()
  
  ElMessage.info('已取消所有更改')
}

// 撤销
const undo = () => {
  if (canvasTableRef.value) {
    canvasTableRef.value.undo()
    updateChangeStatus()
  }
}

// 重做
const redo = () => {
  if (canvasTableRef.value) {
    canvasTableRef.value.redo()
    updateChangeStatus()
  }
}

// 插入行
const insertRow = () => {
  if (!canvasTableRef.value) return
  
  // 获取插入位置
  let insertIndex = props.data.length
  if (selectedRows.value.length > 0) {
    insertIndex = Math.max(...selectedRows.value) + 1
  }
  
  // 创建空行
  const newRow = {}
  props.columns.forEach(col => {
    newRow[col.field] = null
  })
  
  canvasTableRef.value.insertRow(insertIndex, newRow)
  updateChangeStatus()
  
  ElMessage.success('已插入新行')
}

// 删除选中行
const deleteRows = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请先选择要删除的行')
    return
  }
  
  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedRows.value.length} 行数据吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 使用批量删除方法
    const table = canvasTableRef.value?.getTable()
    if (table) {
      // 获取要删除的行的数据
      const rowsToDelete = selectedRows.value.map(rowIndex => {
        return {
          index: rowIndex,
          data: props.data[rowIndex]
        }
      }).filter(item => item.data) // 过滤掉不存在的行
      
      // 发送立即删除事件
      if (rowsToDelete.length > 0) {
        emit('delete-rows', rowsToDelete)
        // 表格UI上也执行删除操作
        table.deleteRows(selectedRows.value)
        updateChangeStatus()
      }
      
      // 删除提示由处理实际数据库操作的父组件负责
    }
  }).catch(() => {
    // 用户取消
  })
}

// 打开查找替换对话框
const openFindReplace = () => {
  findReplaceVisible.value = true
  
  // 如果有选中的文本，将其作为默认查找内容
  if (selectedCells.value.length === 1 && canvasTableRef.value) {
    const cell = selectedCells.value[0]
    const table = canvasTableRef.value.getTable()
    if (table) {
      const value = table.getCellValue(cell.row, cell.col)
      if (value) {
        findReplaceForm.value.findText = String(value)
      }
    }
  }
  
  performFind()
}

// 执行查找
const performFind = () => {
  if (!findReplaceForm.value.findText || !canvasTableRef.value) {
    findResults.value = { matches: [], current: -1, total: 0 }
    return
  }
  
  const table = canvasTableRef.value.getTable()
  if (!table) return
  
  const matches = []
  const searchText = findReplaceForm.value.findText
  const caseSensitive = findReplaceForm.value.caseSensitive
  const wholeWord = findReplaceForm.value.wholeWord
  const useRegex = findReplaceForm.value.useRegex
  
  // 构建搜索模式
  let searchPattern
  if (useRegex) {
    try {
      searchPattern = new RegExp(searchText, caseSensitive ? 'g' : 'gi')
    } catch (e) {
      ElMessage.error('正则表达式无效')
      return
    }
  } else {
    const escapedText = searchText.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
    const pattern = wholeWord ? `\\b${escapedText}\\b` : escapedText
    searchPattern = new RegExp(pattern, caseSensitive ? 'g' : 'gi')
  }
  
  // 获取搜索范围
  let searchRows = []
  let searchCols = []
  
  if (findReplaceForm.value.scope === 'column' && selectedCells.value.length > 0) {
    // 选中列
    const cols = new Set(selectedCells.value.map(cell => cell.col))
    searchCols = Array.from(cols)
    searchRows = Array.from({ length: props.data.length }, (_, i) => i)
  } else if (findReplaceForm.value.scope === 'selection' && selectedCells.value.length > 0) {
    // 选中区域
    selectedCells.value.forEach(cell => {
      if (!searchRows.includes(cell.row)) searchRows.push(cell.row)
      if (!searchCols.includes(cell.col)) searchCols.push(cell.col)
    })
  } else {
    // 整个表格
    searchRows = Array.from({ length: props.data.length }, (_, i) => i)
    searchCols = Array.from({ length: props.columns.length }, (_, i) => i)
  }
  
  // 执行搜索
  searchRows.forEach(row => {
    searchCols.forEach(col => {
      const value = table.getCellValue(row, col)
      if (value && String(value).match(searchPattern)) {
        matches.push({ row, col, value: String(value) })
      }
    })
  })
  
  findResults.value = {
    matches,
    current: matches.length > 0 ? 0 : -1,
    total: matches.length
  }
  
  // 跳转到第一个匹配项
  if (matches.length > 0) {
    highlightMatch(0)
  }
}

// 高亮匹配项
const highlightMatch = (index) => {
  if (index >= 0 && index < findResults.value.matches.length) {
    const match = findResults.value.matches[index]
    const table = canvasTableRef.value?.getTable()
    if (table) {
      table.selectCell(match.row, match.col)
      table.scrollToCell(match.row, match.col)
      findResults.value.current = index
    }
  }
}

// 查找下一个
const findNext = () => {
  if (findResults.value.total === 0) {
    performFind()
    return
  }
  
  const nextIndex = (findResults.value.current + 1) % findResults.value.total
  highlightMatch(nextIndex)
}

// 查找上一个
const findPrevious = () => {
  if (findResults.value.total === 0) {
    performFind()
    return
  }
  
  const prevIndex = (findResults.value.current - 1 + findResults.value.total) % findResults.value.total
  highlightMatch(prevIndex)
}

// 替换当前
const replaceOne = () => {
  if (findResults.value.current < 0 || findResults.value.current >= findResults.value.matches.length) {
    ElMessage.warning('没有找到匹配项')
    return
  }
  
  const match = findResults.value.matches[findResults.value.current]
  const replaceText = findReplaceForm.value.replaceText
  const table = canvasTableRef.value?.getTable()
  
  if (table) {
    table.setCellValue(match.row, match.col, replaceText)
    
    // 移除当前匹配项并查找下一个
    findResults.value.matches.splice(findResults.value.current, 1)
    findResults.value.total = findResults.value.matches.length
    
    if (findResults.value.total > 0) {
      const nextIndex = Math.min(findResults.value.current, findResults.value.total - 1)
      highlightMatch(nextIndex)
    } else {
      findResults.value.current = -1
    }
    
    updateChangeStatus()
  }
}

// 全部替换
const replaceAll = () => {
  if (findResults.value.total === 0) {
    ElMessage.warning('没有找到匹配项')
    return
  }
  
  ElMessageBox.confirm(
    `确定要替换所有 ${findResults.value.total} 个匹配项吗？`,
    '全部替换',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    const replaceText = findReplaceForm.value.replaceText
    const table = canvasTableRef.value?.getTable()
    
    if (table) {
      // 执行所有替换
      findResults.value.matches.forEach(match => {
        table.setCellValue(match.row, match.col, replaceText)
      })
      
      ElMessage.success(`已替换 ${findResults.value.matches.length} 个匹配项`)
      
      // 清空查找结果
      findResults.value = { matches: [], current: -1, total: 0 }
      findReplaceVisible.value = false
      
      updateChangeStatus()
    }
  })
}

// 监听显示行号选项变化
watch(showLineNumbers, () => {
  if (canvasTableRef.value) {
    const table = canvasTableRef.value.getTable()
    if (table) {
      table.toggleRowNumbers(showLineNumbers.value)
    }
  }
})

// 监听高亮修改选项变化
watch(showModifiedCells, () => {
  if (canvasTableRef.value) {
    const table = canvasTableRef.value.getTable()
    if (table) {
      table.setTheme({
        modifiedBgColor: showModifiedCells.value ? '#fffbe6' : '#fff'
      })
    }
  }
})

// 监听分页信息变化
watch([() => props.currentPage, () => props.pageSize], ([newPage, newPageSize]) => {
  if (canvasTableRef.value) {
    const table = canvasTableRef.value.getTable()
    if (table) {
      table.setPageInfo(newPage, newPageSize)
    }
  }
})

// 生命周期钩子
onMounted(() => {
  // 添加全局键盘事件监听
  document.addEventListener('keydown', handleGlobalKeyDown)

  // 组件挂载后恢复行高设置
  nextTick(() => {
    if (canvasTableRef.value) {
      const table = canvasTableRef.value.getTable()
      if (table?.eventManager) {
        // 恢复保存的行高设置
        const rowHeights = JSON.parse(localStorage.getItem('table-row-heights') || '{}')
        const tableId = `${props.currentPage}_${props.pageSize}`
        const savedHeights = rowHeights[tableId] || {}
        
        Object.entries(savedHeights).forEach(([row, height]) => {
          table.eventManager.setRowHeight(parseInt(row), height)
        })
      }
    }
  })
})

onUnmounted(() => {
  // 移除全局键盘事件监听
  document.removeEventListener('keydown', handleGlobalKeyDown)
})

// 处理全局键盘事件
const handleGlobalKeyDown = (e) => {
  // 如果当前处于编辑状态或焦点在输入框，不处理快捷键
  if (e.target instanceof HTMLInputElement || 
      e.target instanceof HTMLTextAreaElement ||
      e.target instanceof HTMLSelectElement) {
    return
  }

  // Ctrl+S: 保存更改
  if ((e.ctrlKey || e.metaKey) && e.key === 's') {
    e.preventDefault() // 阻止浏览器默认的保存页面行为
    if (hasChanges.value) {
      saveChanges()
      ElMessage.success('已保存所有更改')
    }
    return
  }

  // Ctrl+Z: 撤销
  if ((e.ctrlKey || e.metaKey) && !e.shiftKey && e.key === 'z') {
    e.preventDefault()
    undo()
    return
  }

  // Ctrl+Y 或 Ctrl+Shift+Z: 重做
  if ((e.ctrlKey || e.metaKey) && 
      ((e.key === 'y') || (e.shiftKey && e.key === 'z'))) {
    e.preventDefault()
    redo()
    return
  }

  // Ctrl+N: 插入新行
  if ((e.ctrlKey || e.metaKey) && e.key === 'n') {
    e.preventDefault()
    insertRow()
    return
  }

  // Delete或Backspace: 删除选中的行(添加确认)
  if ((e.key === 'Delete' || e.key === 'Backspace') && 
      selectedRows.value.length > 0 && 
      !(e.target instanceof HTMLInputElement || e.target instanceof HTMLTextAreaElement)) {
    // 让表格内部的Delete操作处理单元格内容删除
    // 这里只处理行删除，并且添加确认步骤
    ElMessageBox.confirm(
      `确定要删除选中的 ${selectedRows.value.length} 行数据吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    ).then(() => {
      deleteRows()
    }).catch(() => {
      // 用户取消
    })
    return
  }

  // Ctrl+F: 查找替换
  if ((e.ctrlKey || e.metaKey) && e.key === 'f') {
    e.preventDefault()
    openFindReplace()
    return
  }
}

// 暴露方法给父组件
defineExpose({
  refresh: () => canvasTableRef.value?.refresh(),
  save: saveChanges,
  cancel: cancelChanges,
  hasChanges: () => hasChanges.value,
  // 添加更新单个单元格的方法
  updateCell: (row, col, value) => {
    const table = canvasTableRef.value?.getTable()
    if (table) {
      table.setCellValue(row, col, value)
      updateChangeStatus()
    }
  }
})
</script>

<style scoped>
.database-table {
  background: white;
  position: relative;
}

.table-toolbar {
  min-height: 40px;
}

.table-statusbar {
  min-height: 24px;
  font-size: 11px;
}

/* 查找替换对话框样式 */
.find-status {
  padding: 10px;
  background: #f5f7fa;
  border-radius: 4px;
  text-align: center;
  color: #606266;
  font-size: 13px;
  margin-top: 10px;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-form-item) {
  margin-bottom: 18px;
}

:deep(.el-checkbox) {
  margin-right: 20px;
}
</style> 